package jp.wug.samples.pragprog;

import jp.wug.PageFlow;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class Checkout {
    Store.Cart cart;
    OrdersEntity order = new OrdersEntity();
    EntityManager entityManager;
    Provider<PageFlow> pageFlowProvider;
    Provider<Store> storeProvider;

    @Inject
    public Checkout(Store.Entities entities, Store.Cart cart, Provider<PageFlow> pageFlowProvider, Provider<Store> storeProvider) {
        this.entityManager = entities.get();
        this.cart = cart;
        this.pageFlowProvider = pageFlowProvider;
        this.storeProvider = storeProvider;
    }

    public Store.Cart getCart() {
        return cart;
    }

    public Checkout getForm() {
        return this;
    }

    public OrdersEntity getOrder() {
        return order;
    }

    public void submit() {
        EntityTransaction transaction = entityManager.getTransaction();
        try {
            transaction.begin();
            entityManager.persist(order);
            transaction.commit();
        } catch (RuntimeException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        cart.clear();
        Store store = storeProvider.get();
        store.setMessage("thankyou");
        pageFlowProvider.get().redirectTo(Store.class, store);
    }
}
